package com.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.dao.AttrAttrgroupRelationDao;
import com.mall.dao.AttrGroupDao;
import com.mall.dao.CategoryDao;
import com.mall.entity.*;
import com.mall.service.*;
import com.mall.vo.AttrGroupVo;
import com.mall.vo.AttrRespVo;
import com.mall.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.utils.PageUtils;
import com.mall.common.utils.Query;

import com.mall.dao.AttrDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, Attr> implements AttrService {


    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;


    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        Attr attrEntity = new Attr();
        BeanUtils.copyProperties(attr,attrEntity); //赋值属性   复制
        this.save(attrEntity);
        //保存关联关系
        AttrAttrgroupRelation relationEntity = new AttrAttrgroupRelation();
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        relationEntity.setAttrId(attrEntity.getAttrId());
        attrAttrgroupRelationDao.insert(relationEntity);
    }

    @Override
    public IPage<AttrRespVo> queryPage(Map<String, String> map, Long catelogId) {
        Integer currentPage = Integer.valueOf(map.get("page"));
        Integer pageSize = Integer.valueOf(map.get("limit"));
        String key = map.get("key");
        QueryWrapper<Attr> queryWrapper = new QueryWrapper<>();
        if (catelogId != 0){
            queryWrapper.eq("category_id",catelogId);
        }
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        List<Attr> attrs = attrDao.selectList(queryWrapper);

        List<AttrRespVo> attrRespVoList = attrs.stream().map((attr) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attr, attrRespVo);
            AttrAttrgroupRelation relation = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelation>().eq("attr_id", attrRespVo.getAttrId()));
            if (relation != null) {
                AttrGroup attrGroup = attrGroupDao.selectById(relation.getAttrGroupId());
                attrRespVo.setGroupName(attrGroup.getAttrGroupName());
            }

            Category category = categoryDao.selectById(attr.getCategoryId());
            if (category != null) {
                attrRespVo.setCategoryName(category.getName());
            }

//            System.out.println(attrRespVo);
            return attrRespVo;
        }).collect(Collectors.toList());
        IPage<AttrRespVo> page = listToPage(attrRespVoList, currentPage, pageSize);

        return page;
    }


    /**
     * 传入attrid 得到respVo
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        Attr attr = this.getById(attrId);
        BeanUtils.copyProperties(attr,attrRespVo);
        //先查找分组信息  在关联表中查找

        //在关联表根据attr_id查询 AttrAttrgroupRelation对象
        AttrAttrgroupRelation relation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelation>().eq("attr_id", attr.getAttrId()));
        if (relation != null){
            //根据属性分组来查分组id
            attrRespVo.setAttrGroupId(relation.getAttrGroupId());
            //根据分组id来查属性分组表
            AttrGroup attrGroup = attrGroupDao.selectById(relation.getAttrGroupId());
            if (attrGroup != null){
                //再根据id查name
                attrRespVo.setAttrName(attrGroup.getAttrGroupName());
            }
        }

        //设置分类信息
        Long categoryId = attr.getCategoryId();
        Long[]catelogPath =  categoryService.findCatelogPath(categoryId);
        attrRespVo.setCatelogPath(catelogPath);
        Category category = categoryDao.selectById(categoryId);
        if (category != null){
            attrRespVo.setCategoryName(category.getName());
        }
        return attrRespVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        Attr attrEntity = new Attr();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        //修改分组关联
        AttrAttrgroupRelation relation = new AttrAttrgroupRelation();

        relation.setAttrGroupId(attr.getAttrGroupId());
        relation.setAttrId(attr.getAttrId());
        Long count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelation>().eq("attr_id", attr.getAttrId()));

        if (count>0){
            attrAttrgroupRelationDao.update(relation,new UpdateWrapper<AttrAttrgroupRelation>().eq("attr_id",attr.getAttrId()));
        }else {
            attrAttrgroupRelationDao.insert(relation);
        }

    }

    @Override
    public List<Attr> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelation> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelation>().eq("attr_group_id", attrGroupId));

        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if(attrIds == null || attrIds.size() == 0){
            return null;
        }
        Collection<Attr> attrEntities = this.listByIds(attrIds);
        return (List<Attr>) attrEntities;
    }

    @Override
    public List<AttrGroupVo> selectListGroupAttr(Long spuId) {
        //先根据商品spu_id查询查询xy_product_attr_value
        List<ProductAttrValue> spu_id = productAttrValueService.list(new QueryWrapper<ProductAttrValue>().eq("spu_id", spuId));
        List<AttrGroupVo> attrGroupVos= new ArrayList<>();
        for (ProductAttrValue productAttrValue : spu_id) {
            AttrGroupVo attrGroupVo = new AttrGroupVo();

            attrGroupVo.setKey(productAttrValue.getAttrName());
            attrGroupVo.setValue(productAttrValue.getAttrValue());



            Long attrId = productAttrValue.getAttrId();
            List<Attr> attr_id = attrService.list(new QueryWrapper<Attr>().eq("attr_id", attrId));
            for (Attr attr : attr_id) {
                Long attrids = attr.getAttrId();
                List<AttrAttrgroupRelation> list = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelation>().eq("attr_id", attrids));
                for (AttrAttrgroupRelation relation : list) {
                    Long attrGroupId = relation.getAttrGroupId();
                    List<AttrGroup> attr_group_id = attrGroupService.list(new QueryWrapper<AttrGroup>().eq("attr_group_id", attrGroupId));
                    for (AttrGroup attrGroup : attr_group_id) {
                        String attrGroupName = attrGroup.getAttrGroupName();
                        attrGroupVo.setGroupName(attrGroupName);
                    }
                }

            }

            attrGroupVos.add(attrGroupVo);
        }
        //根据xy_product_attr_value 的attr_id字段来查xy_attr

        //根据attr 和attrgroup关联来查attr_relation


//        System.out.println(attrGroupVos);
        return attrGroupVos;


    }


    public static IPage<AttrRespVo> listToPage(List<AttrRespVo> list, int pageNum, int pageSize){
        List<AttrRespVo> pageList = new ArrayList<>();
        int curIdx = pageNum > 1 ? (pageNum - 1) * pageSize : 0;
        for (int i = 0; i < pageSize && curIdx + i < list.size(); i++) {
            pageList.add(list.get(curIdx + i));
        }
        IPage<AttrRespVo> page = new Page<>(pageNum, pageSize);
        page.setRecords(pageList);
        page.setTotal(list.size());
        return page;
    }

}